package com.motu.monstercity.server.game.web;

import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class RouterManager extends BaseWebHandler {
    private final static Logger logger = LoggerFactory.getLogger(RouterManager.class);
    private static final String HANDLER_PATH = "com.motu.monstercity.server.game.web.";
    private static final String HANDLER_PATH_UTILITY = "com.motu.vertx.module.utility.webhandler.";

    public static void handler(RoutingContext routingContext, WebClient webClient){
        try {
            String path = routingContext.request().path();
            JsonObject obj = routingContext.body().asJsonObject();
            JsonObject json = obj.getJsonObject("pdata");
            String token = obj.getString("token");
            String adminName = obj.getString("user");

            //System.out.println("json:" + json);
            // todo 登录校验

            String p1 = path.substring(7);//去掉/admin/
            int index = p1.indexOf('/');
            String className = p1.substring(0, index);
            String methodName = p1.substring(index+1).replace("/", "_");

            String strClass = Tool.captureName(className) + "Handler";
            String strMethod = methodName;
            Class<?> threadClazz;
            try {
                String classPath = isUtilityHandler(className) ? HANDLER_PATH_UTILITY : HANDLER_PATH;
                threadClazz = Class.forName(classPath + strClass);

                Method method = threadClazz.getMethod(strMethod,  new Class[] { RoutingContext.class,JsonObject.class,String.class,WebClient.class });
                method.invoke(null,new Object[] { routingContext,json,adminName,webClient });
            } catch (Exception e) {
                logger.error(Tool.getException(e));
                sendHttpResponseError(routingContext.response(), "router error:"+e.getMessage()+"."+methodName);
            }
        } catch (Exception e) {
            sendHttpResponseError(routingContext.response(), "逻辑处理错误");
            logger.error(Tool.getException(e));
        }
    }

    /***
     * 判断是否调用utility.webhandler 下的对应的handler文件的接口
     * @param className 类名
     * @return 判断结果 true: com.motu.vertx.module.utility.webhandler;, false:com.motu.monstercity.server.game.web.
     */
    public static boolean isUtilityHandler(String className){
        String classNames[] = new String[]{"serveropen"};
        for (int i=0; i<classNames.length; i++) {
            if (className.equalsIgnoreCase(classNames[i])) {
                return true;
            }
        }
        return false;
    }
}
